package com.tyj.movie.exception;

import com.tyj.movie.constant.AjaxConstant;
import com.tyj.movie.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 日期: 2021/6/29 11:02
 * 作者: 谭友杰
 * 类说明:
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.tyj.movie.controller")
public class GlobalException {

    @ExceptionHandler(value = BindException.class)
    public R handleVaildException(BindException e){
        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult=e.getBindingResult();
        Map<String,String> map=new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        R error = R.error(AjaxConstant.AjAX_PAREMETER_ERROR.getCode(), AjaxConstant.AjAX_PAREMETER_ERROR.getMsg());
        error.put("data",map);
        return error;
    }

}
